package com.xiaoxx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoxx.coin.enums.ContractTypeEnum;
import com.xiaoxx.coin.impl.UMFuturesClientImpl;
import com.xiaoxx.coin.po.Filter;
import com.xiaoxx.coin.po.Symbol;
import com.xiaoxx.coin.po.res.ExchangeInfoResponse;
import com.xiaoxx.mapper.BinanceExchangeinfoMapper;
import com.xiaoxx.model.entity.coin.BinanceExchangeinfo;
import com.xiaoxx.service.BinanceExchangeinfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author HX
 * @since 2024-11-28
 */
@Service
@Slf4j
public class BinanceExchangeinfoServiceImpl extends ServiceImpl<BinanceExchangeinfoMapper, BinanceExchangeinfo> implements BinanceExchangeinfoService {

    @Override
    public void refreshExchangeInfo() {
        this.remove(new LambdaQueryWrapper<>());
        UMFuturesClientImpl client = new UMFuturesClientImpl();
        ExchangeInfoResponse exchangeInfoResponse = client.market().exchangeInfo();
        if (exchangeInfoResponse != null && exchangeInfoResponse.getSymbols() != null) {
            List<Symbol> symbols = exchangeInfoResponse.getSymbols();
            List<BinanceExchangeinfo> collect = symbols.stream().filter(i -> i.getContractType().equals(ContractTypeEnum.PERPETUAL.getCode())).map(i -> {
                BinanceExchangeinfo entity = new BinanceExchangeinfo();
                Filter priceFilter = i.getFilters().stream().filter(j -> j.getFilterType().equals("PRICE_FILTER")).findFirst().get();
                if (priceFilter != null && StringUtils.hasLength(priceFilter.getTickSize())) {
                    entity.setPricePrecision(new BigDecimal(priceFilter.getTickSize()).stripTrailingZeros().scale());
                }
                entity.setSymbol(i.getSymbol());
                entity.setPair(i.getPair());
                entity.setContractType(i.getContractType());
                entity.setQuantityPrecision(i.getQuantityPrecision());
                return entity;
            }).collect(Collectors.toList());
            this.saveBatch(collect);
            log.info("获取到{}个交易对", symbols.size());
        }
    }


}
